const { mouse, straightTo, screen } = require("@nut-tree-fork/nut-js");
const screenshot = require('desktop-screenshot');
const Jimp = require('jimp');
const fs = require('fs');

async function getScreenResolution() {
    try {
        const width = await screen.width();
        const height = await screen.height();
        console.log(`📱 检测到屏幕分辨率: ${width} x ${height}`);
        return { width, height };
    } catch (error) {
        console.log('⚠️ nut.js 无法获取屏幕分辨率，使用默认值');
        return { width: 1920, height: 1080 };
    }
}

async function takeScreenshot() {
    try {
        console.log('📸 正在截取屏幕...');
        return new Promise((resolve, reject) => {
            screenshot(path.join(__dirname, '..', 'static', 'temp_screenshot.png'), (error, complete) => {
                if (error) {
                    reject(error);
                } else {
                    console.log('✅ 截图完成');
                    resolve(path.join(__dirname, '..', 'static', 'temp_screenshot.png'));
                }
            });
        });
    } catch (error) {
        console.error('截图失败:', error);
        throw error;
    }
}

async function findImageOnScreen(templatePath, confidence = 0.5) {
    try {
        console.log('📸 正在截取屏幕...');
        const screenshotPath = await takeScreenshot();
        
        console.log('🖼️ 正在加载模板图像...');
        console.log(`模板路径: ${templatePath}`);
        console.log(`截图路径: ${screenshotPath}`);
        
        // 检查文件是否存在
        if (!fs.existsSync(templatePath)) {
            throw new Error(`模板图片不存在: ${templatePath}`);
        }
        
        if (!fs.existsSync(screenshotPath)) {
            throw new Error(`截图文件不存在: ${screenshotPath}`);
        }
        
        // 获取文件信息
        const templateStats = fs.statSync(templatePath);
        const screenshotStats = fs.statSync(screenshotPath);
        
        console.log(`模板图片大小: ${templateStats.size} bytes`);
        console.log(`截图大小: ${screenshotStats.size} bytes`);
        
        // 获取实际屏幕分辨率
        const screenSize = await getScreenResolution();
        console.log(`🔄 屏幕分辨率: ${screenSize.width} x ${screenSize.height}`);
        
        // 实现真正的图像查找功能
        console.log('🔍 开始真正的图像查找...');
        
        // 使用 Jimp 进行图像匹配
        const result = await findImageWithJimp(templatePath, screenshotPath, confidence);
        
        if (result) {
            console.log(`🎯 找到目标图片，位置: (${result.x}, ${result.y})`);
            console.log(`📏 匹配度: ${(result.confidence * 100).toFixed(2)}%`);
            return {
                x: result.x,
                y: result.y,
                width: result.width,
                height: result.height,
                center: {
                    x: result.x + Math.floor(result.width / 2),
                    y: result.y + Math.floor(result.height / 2)
                }
            };
        }
        
        throw new Error('无法找到目标图片');
        
    } catch (error) {
        console.error('图像匹配失败:', error);
        throw error;
    }
}

async function findImageWithJimp(templatePath, screenshotPath, confidence = 0.5) {
    try {
        console.log('🔍 使用 Jimp 进行图像匹配...');
        
        // 加载模板图片和截图
        const templateImage = await Jimp.read(templatePath);
        const screenshotImage = await Jimp.read(screenshotPath);
        
        const templateWidth = templateImage.getWidth();
        const templateHeight = templateImage.getHeight();
        const screenshotWidth = screenshotImage.getWidth();
        const screenshotHeight = screenshotImage.getHeight();
        
        console.log(`📏 模板图片尺寸: ${templateWidth} x ${templateHeight}`);
        console.log(`📏 截图尺寸: ${screenshotWidth} x ${screenshotHeight}`);
        
        let bestMatch = {
            x: 0,
            y: 0,
            confidence: 0
        };
        
        // 优化步长，提高搜索效率
        const stepSize = Math.max(1, Math.floor(Math.min(templateWidth, templateHeight) / 8));
        console.log(`🔍 搜索步长: ${stepSize} 像素`);
        
        console.log('🔍 开始像素级图像匹配...');
        
        // 在截图中搜索模板图片
        for (let y = 0; y <= screenshotHeight - templateHeight; y += stepSize) {
            for (let x = 0; x <= screenshotWidth - templateWidth; x += stepSize) {
                let matchScore = 0;
                let totalPixels = 0;
                
                // 优化像素采样，减少计算量
                const sampleStep = Math.max(1, Math.floor(Math.min(templateWidth, templateHeight) / 20));
                
                for (let ty = 0; ty < templateHeight; ty += sampleStep) {
                    for (let tx = 0; tx < templateWidth; tx += sampleStep) {
                        try {
                            const screenshotPixel = screenshotImage.getPixelColor(x + tx, y + ty);
                            const templatePixel = templateImage.getPixelColor(tx, ty);
                            
                            // 计算颜色差异
                            const screenRgb = Jimp.intToRGBA(screenshotPixel);
                            const templateRgb = Jimp.intToRGBA(templatePixel);
                            
                            const diff = Math.sqrt(
                                Math.pow(screenRgb.r - templateRgb.r, 2) +
                                Math.pow(screenRgb.g - templateRgb.g, 2) +
                                Math.pow(screenRgb.b - templateRgb.b, 2)
                            );
                            
                            // 使用颜色差异阈值判断匹配
                            if (diff < 80) { // 可以调整这个阈值
                                matchScore++;
                            }
                            totalPixels++;
                        } catch (pixelError) {
                            // 忽略边界像素错误
                            continue;
                        }
                    }
                }
                
                const currentConfidence = matchScore / totalPixels;
                
                if (currentConfidence > bestMatch.confidence) {
                    bestMatch = {
                        x: x,
                        y: y,
                        confidence: currentConfidence
                    };
                    
                    console.log(`🔍 发现更好的匹配: (${x}, ${y}) - 置信度: ${(currentConfidence * 100).toFixed(2)}%`);
                    
                    // 如果找到很好的匹配，提前退出
                    if (currentConfidence > 0.85) {
                        console.log('🎯 找到高置信度匹配，提前退出搜索');
                        break;
                    }
                }
            }
            
            // 如果找到很好的匹配，提前退出
            if (bestMatch.confidence > 0.85) {
                break;
            }
        }
        
        console.log(`🎯 最佳匹配置信度: ${(bestMatch.confidence * 100).toFixed(2)}%`);
        
        if (bestMatch.confidence >= confidence) {
            return {
                x: bestMatch.x,
                y: bestMatch.y,
                width: templateWidth,
                height: templateHeight,
                confidence: bestMatch.confidence
            };
        }
        
        console.log('❌ 未找到足够好的匹配');
        return null;
        
    } catch (error) {
        console.error('Jimp 图像匹配失败:', error);
        throw error;
    }
}

async function clickTarget() {
    try {
        console.log('🔍 开始查找目标图片...');
        
        // 使用 Jimp 图像匹配算法查找目标图片
        const buttonImage = await findImageOnScreen("target.png", 0.6);
        
        if (buttonImage) {
            console.log("✅ 找到目标，位置:", buttonImage);
            console.log("🎯 目标中心点:", buttonImage.center);
            
            // 移动鼠标到目标中心并点击
            await mouse.move(straightTo({ x: buttonImage.center.x, y: buttonImage.center.y }));
            await mouse.leftClick();
            console.log("✅ 点击完成");
        } else {
            console.log("❌ 未找到目标图片");
        }
        
    } catch (err) {
        console.error("❌ 查找失败:", err.message);
        process.exit(1);
    }
}

// 执行主函数
clickTarget().catch(err => {
    console.error("❌ 程序执行失败:", err);
    process.exit(1);
});